<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Wechat\Controller;
use Think\Controller;
use SimpleXMLElement;

/**
 * 前台公共控制器
 * 为防止多分组Controller名称冲突，公共Controller名称统一使用分组名称
 */
class WechatController extends Controller {

	/* 空操作，用于输出404页面 */
	public function _empty(){
		$this->error('当前页面不存在',U('service/index'));
	}


    protected function _initialize(){
		//session(null);
    	session('[start]');
    	
        /* 读取站点配置 */
        $config = api('Config/lists');
        C($config); //添加配置

        if(!C('WEB_SITE_CLOSE')){
            $this->error('站点已经关闭，请稍后访问~');
        }
        
        //$memberid = getuserid();
        $memberid = 2;
        //用户账号id，不能叫UID是因为会和登录的用户的UID重复
        define('MID', $memberid);
        //用户的公众账号id，目前是一个用户一个账号的情况，所以是WID == MID
        define('WID', MID);
        //获取参数配置
        $userconfigLogic = D('Userconfig','Logic');
        $userconfiginfo = $userconfigLogic->where(array('uid'=>$memberid))->find();
        session('userconfiginfo',$userconfiginfo);
        
        if(ACTION_NAME != 'notify'){
        	$signature = I('get.signature');
        	if($signature==null){
        		$userconfiginfo['wechataccounttype']=2;
        		$code = $_GET['code'];
        		$userinfo = session('userinfo');


 
				   $userinfo = array(


        		 		'subscribe' => 1,

        				'openid' => 'osmtyt92i-nm-PoEDDYi-1kBh5C',


        				'nickname' => '每一天111111',
        				'sex' => 1,
        				'language' => 'zh_CN',
        				'city' => '天津',
        				'province' => '天津',
        				'country' => '南开',
        				'headimgurl' => 'http://wx.qlogo.cn/mmopen/Q3auHgzwzM6ibNxabmRGHia6eNgoH1rI946icNtpT0P8aE4g124qcHm8w5oMEedzb9B6iaPHgKKXX1nFPPXicA1hXlw/0',
        				'subscribe_time' => 1399720293,
        				'remark' => '',
        		);      





        		if($userinfo['openid'] == null||$userinfo['nickname'] == null){
        			$userinfo = $this->getUserInfo($code);
        		}
        		if($memberid == 2 && $userinfo['openid'] != null){
        			$this->checkOpenid($userinfo);
        			
        		}
        		
        		session('userinfo',$userinfo);
        		 
        		if($userconfiginfo['wechataccounttype']== 2 && $userinfo['openid'] == null){
        			$url = get_url();
        			$rurl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$userconfiginfo['appid'].'&redirect_uri='.$url.'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
        			redirect($rurl);
        			 
        		}
        	}
        }

       
    }
    /**
     * 根据openid和vipid判断是否生成新的用户
     * @date: 2014-12-11
     * @author: 明
     * @return:
     */
	public function checkOpenid($userinfo){
    	$vipLogic = D('Vip','Logic');
    	$map = array(
    			'openid' => $userinfo['openid']
    	);
    	$vip = $vipLogic->where($map)->find();
    	if($vip['id'] == null&&$userinfo['nickname']){  //因为通过分享点进去连接此时只有openid，会生成一个只有openid的user
    		$data = array(
    				'openid' => $userinfo['openid'],
    				'headimgurl' => $userinfo['headimgurl'],
    				'nickname' => $userinfo['nickname'],
    				'source' =>	'微信',
    				'registertime'	=>	time(),
    		);
    		$data['clubcard']= $this->createClubCard(2,6);
    		$res = $vipLogic->add($data);
    		if(!empty($res)){
    			$vip = $vipLogic->where($map)->find();
    			//$vip['id'] = $res['id'];
    		}
    		//生成新用户之后给该用户首次关注的积分
    		if($res){
    			$incomeLogic = D('DistributionIncome','Logic');
    			$percentageLogic = D('DistributionPercentage','Logic');
    			$percent=$percentageLogic->find();
    			$adata=array(
    					'accid'		=> $vip['id'],
    					'createtime'=>date(time()),
    					'integral'  =>floatval($percent['firstconcern']),
    					'type'      =>'share',
    					'openid'    =>$userinfo['openid'],
    			);
    			$incomeLogic->add($adata);
    			
    			//首次关注送优惠券
    			$myCouponLogic = D ( 'mycoupon', 'Logic' );
    			$couponLogic = D ( 'coupon', 'Logic' );
    			$coupon=$couponLogic->where(array('firstconcern'=>1))->field('id,coupon_price,coupon_num,coupon_etime,integral')->select();
				foreach($coupon as $key=>$value){
					$myCouponData = array (
    					'price'=>$coupon[$key]['coupon_price'],
    					'openid'=>$userinfo['openid'],
    					'cid'=>$coupon[$key]['id'],
    			);
    			$myCouponLogic->add ( $myCouponData );
				}
    			
    		}
    		
    		
    		//
    		
    		
    	}/* else if($vip['nickname'] == null&&$vip['id'] != null){
    		$data = array(
    				'openid' => $userinfo['openid'],
    				'headimgurl' => $userinfo['headimgurl'],
    				'nickname' => $userinfo['nickname'],
    				'source' =>	'微信',
    				'registertime'	=>	time(),
    		);
    		$data['clubcard']= $this->createClubCard(2,6);
    		$res = $vipLogic->where(array('id'=>$vip['id']))->save($data);
    		if(!empty($res)){
    			$vip['id'] = $res['id'];
    		}
    	} */
    	$user['id'] = $vip['id'];
    	define('VIPUID', $vip['id']);
    	 
    }
    
    /**
    * 判断用户是否同意用户许可
    * @date: 2015-1-28
    * @author: 明
    * @return:
    */
	protected function isvipauth($url){
		$userinfo = session('userinfo');
		$vipLogic = D('Vip','Logic');
		$vip = $vipLogic->where(array('openid'=>$userinfo['openid']))->find();
		if($vip['authstatus'] == 0){
			redirect(U('service/agreement'));
		}
	}   
	
	
	/* 用户登录检测 */
	/**
	* 登录成功后跳转到的url
	* @date: 2015-1-27
	* @author: 明
	* @return:
	*/
	protected function login($url){
		
		$user = session('user_auth');
		
		/* 用户登录检测 */
		//防止不同微信号的会员串号
		/* if(!is_login() || WID != $user['wid']){
			session('jumpurl',$url);
			redirect(U('Login/loginGuest'));
			exit;
		} */
// 		dump($user);exit();
		define('VIPUID', $user['id']);
	}
	
	/**
	 * 生成验证码
	 * @date: 2014-10-20
	 * @author: 明
	 * @return:
	 */
	public function createVerifycode(){
		$number = "";
		for ($i=0;$i<6;$i++){
			$number .= rand(0,9);
		}
		return $number;
	}
	
	/**
	* 服务号获取用户openid
	* @date: 2014-10-22
	* @author: 明
	* @return:
	*/
	public function getUserInfo($code){
	
		$userinfo = session('userconfiginfo');
		$appid = $userinfo['appid'];
		$appsecret = $userinfo['appsecret'];
	
		//oauth2的方式获得openid
		$access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
		$access_token_json = $this->https_request($access_token_url);
		$access_token_array = json_decode($access_token_json, true);
		$openid = $access_token_array['openid'];
	
		//非oauth2的方式获得全局access token
		$new_access_token = $this->getAccessToken();
	
		//全局access token获得用户基本信息
		$userinfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$new_access_token&openid=$openid";
		$userinfo_json = $this->https_request($userinfo_url);
		$userinfo_array = json_decode($userinfo_json, true);
		return $userinfo_array;
	}
	
	/**
	* 根据
	* @date: 2014-12-26
	* @author: 明
	* @return:
	*/
	public function getInfo($openid){
	
		$userinfo = session('userconfiginfo');
		$appid = $userinfo['appid'];
		$appsecret = $userinfo['appsecret'];
	
		//非oauth2的方式获得全局access token
		$new_access_token = $this->getAccessToken();
		//全局access token获得用户基本信息
		$userinfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$new_access_token&openid=$openid";
		$userinfo_json = $this->https_request($userinfo_url);
		$userinfo_array = json_decode($userinfo_json, true);
		return $userinfo_array;
	}
	
	/**
	* 获取access_token 上次获取时间跟现在差距大于7200秒则重新获取
	* @date: 2015-1-17
	* @author: 明
	* @return:
	*/
	public function getAccessToken(){
		$userconfigLogic = D('Userconfig','Logic');
        $userconfiginfo = $userconfigLogic->where(array('uid'=>WID))->find();
        $time = time();
        $new_access_token = $userconfiginfo['access_token'];
        if($userconfiginfo['access_token'] == null || $time > $userconfiginfo['access_time']+7200){
        	$userinfo = session('userconfiginfo');
        	$appid = $userinfo['appid'];
        	$appsecret = $userinfo['appsecret'];
        	//非oauth2的方式获得全局access token
        	$new_access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
        	$new_access_token_json = $this->https_request($new_access_token_url);
        	$new_access_token_array = json_decode($new_access_token_json, true);
        	$new_access_token = $new_access_token_array['access_token'];
        	$data = array(
        		'access_token' => $new_access_token,
        		'access_time' => time(),
        	);
        	$res = $userconfigLogic->where(array('uid'=>WID))->save($data);
        } 
		
		return $new_access_token;
	}
	
	
	
	public function getTicket($data){
		
		$access_token = $this->getAccessToken();

		$url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;
		
		$res = $this->httpdata($url, $data);

		return $res;
	
	}
	
	
	/**
	* http请求
	* @date: 2015-1-17
	* @author: 明
	* @return:
	*/
	public function https_request($url){
		
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$data = curl_exec($curl);
		if (curl_errno($curl)){return 'ERROR '.curl_error($curl);}
		curl_close($curl);
		return $data;
		
	}
	
	/**
	* http带参数请求
	* @date: 2015-1-31
	* @author: 明
	* @return:
	*/
	public function httpdata($url,$data){
		$data = json_encode($data);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$status = curl_exec($ch);
		curl_close($ch);
		$res = json_decode($status,true);
		return $res;
	}
	
	/**
	* 生成signpackage
	* @date: 2015-1-17
	* @author: 明
	* @return: string $signPackage
	*/
	  public function getSignPackage() {
	    $jsapiTicket = $this->getJsApiTicket();
	    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
	    $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	    $timestamp = time();
	    $nonceStr = $this->createNonceStr();

	    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
	    $string = 'jsapi_ticket='.$jsapiTicket.'&noncestr='.$nonceStr.'&timestamp='.$timestamp.'&url='.$url;
	
	    $signature = sha1($string);
	    //dump($signature);
		$userconfig = session('userconfiginfo');
	    $signPackage = array(
	      "appId"     => $userconfig['appid'],
	      "nonceStr"  => $nonceStr,
	      "timestamp" => $timestamp,
	      "url"       => $url,
	      "signature" => $signature,
	      "rawString" => $string
	    );
	    return $signPackage; 
	  }
	  
	  /**
	  * 生成NonceStr
	  * @date: 2015-1-17
	  * @author: 明
	  * @return:
	  */
	  private function createNonceStr($length = 16) {
	  	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	  	$str = "";
	  	for ($i = 0; $i < $length; $i++) {
	  		$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
	  	}
	  	return $str;
	  }
	  
	  /**
	  *	获取getJsApiTicket
	  * @date: 2015-1-17
	  * @author: 明
	  * @return:
	  */
	  private function getJsApiTicket(){
	  	$uid = WID;
	  	// jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
	  	$filename = C('WEB_ABSOLUTE_URL').'/Public/Wechat/json/jsapi_ticket'.$uid.'.json';
	  	$data = json_decode(file_get_contents($filename));
	  	if ($data->expire_time < time()) {
	  		$accessToken = $this->getAccessToken();
	  		// 如果是企业号用以下 URL 获取 ticket
	  		// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
	  		$url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token='.$accessToken;
	  		$res = json_decode($this->https_request($url));
	  		$ticket = $res->ticket;
	  		if($ticket){
	  			$data->expire_time = time() + 7000;
	  			$data->jsapi_ticket = $ticket;
	  			$fp = fopen($filename, "w");
	  			fwrite($fp, json_encode($data));
	  			fclose($fp);
	  		}
	  	} else {
	  		$ticket = $data->jsapi_ticket;
	  	}
	  
	  	return $ticket;
	  }
	  
	  
	  
	  
	  /**
	  * 推动模板消息并生成log记录
	  * @date: 2015-1-31
	  * @author: 明
	  * @data：$data 模板消息内容  $
	  * @return:$res 返回的数据
	  */
	  public function sendtemplate($data){
	  
	  	$access_token = $this->getAccessToken();
	  	$url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;
		//buchongjilu模板消息的算法	  	
	  	$res = $this->httpdata($url, $data);
	  	//dump($res);
	  
	  }
	  
	  /**
	   * 根据经纬度计算距离
	   * @param $lat经度$lng维度
	   * @return return_type
	   * @author 明
	   * @date 2014-9-23下午3:29:01
	   * @version v1.0.0
	   */
	  public function GetDistance($lat1, $lng1, $lat2, $lng2){
	  	//dump($lat1.' '.$lng1.' '.$lat2.' '.$lng2);
	  	$EARTH_RADIUS = 6378.137;
	  	$radLat1 = $this->rad($lat1);
	  	$radLat2 = $this->rad($lat2);
	  	$a = $radLat1 - $radLat2;
	  	$b = $this->rad($lng1) - $this->rad($lng2);
	  	$s = 2 * asin(sqrt(pow(sin($a/2),2) +
	  			cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)));
	  	$s = $s *$EARTH_RADIUS;
	  	$s = round($s * 10000) / 10000;
	  	return $s;
	  }
	  public function rad($d){
	  	return $d * 3.1415926535898 / 180.0;
	  }
	  
	  /**
	   * 从微信获取上传的图片
	   * @date: 2015-2-2
	   * @author: 明
	   * @return:
	   */
	  public function getimages($url,$filename){
	  	//$url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=r23zFbb0W62KkaMsLZ36wsHrmFlz_dBNnqDNd8X05Cz2iLUG4BUOWGX84P7G6ZKcZmsPNYU9ojvI3p51CT0gU0LLclhrWiEJDL_tKL1O-ew&media_id=B1BjYGcc33fyhPorIx1_KoIOmOy5v6OcrtCZShfmcHKix_D4qOOrmS0LJJk3nUd7';
	  	$return_content = $this->http_get_data($url);
	  	$path = 'Public/Upload/wximgs/'.date('Y',time()).'/'.date('md',time());
	  	if(!is_dir($path)) {
	  		// 尝试创建目录
	  		if(!mkdir($path,0777,true)){
	  			$this->error  =  '上传目录'.$path.'不存在';
	  			return false;
	  		}
	  	}else {
	  		if(!is_writeable($path)) {
	  			$this->error  =  '上传目录'.$path.'不可写';
	  			return false;
	  		}
	  	}
	  	$filename = $path.'/'.$filename;
	  	$fp = @fopen($filename,"a"); //将文件绑定到流 
	  	fwrite($fp,$return_content); //写入文件
	  	return true;
	  }
	  
	  /**
	   * 函数用途描述
	   * @date: 2015-2-2
	   * @author: 明
	   * @return:
	   */
	  function http_get_data($url) {
	  	$ch = curl_init ();
	  	curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
	  	curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
	  	curl_setopt ( $ch, CURLOPT_URL, $url );
	  	ob_start ();
	  	curl_exec ( $ch );
	  	$return_content = ob_get_contents ();
	  	ob_end_clean ();
	  
	  	$return_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
	  	return $return_content;
	  }
	  /**
	   * 接受接口测试版
	   * @date: 2015-2-3
	   * @author: 明
	   * @return:
	   */
	  public function test(){
	  	if(IS_POST){ 
	  	$value = I('post.value');
	  	$testLogic = D('test','Logic');
	  	$data = array(
	  			'config' => serializeMysql($value),
	  			//'config' => $value,
	  	);
	  	$res = $testLogic->add($data);
	  	if($res){
	  		$this->ajaxReturn(array('status'=>1));
	  	}
	  		
	  	}else{
	  		$testLogic = D('test','Logic');
	  		$value = $testLogic->where(array('id'=>4))->find();
	  		//dump($value);
	  		$value = serializeMysql($value['config'],1);
	  		dump($value);
	  	}
	  }
	  
	  public function posttest(){
	  	$this->display();
	  } 
	  
	  /**
	   * http带参数请求
	   * @date: 2015-1-31
	   * @author: 明
	   * @return:
	   */
	  public function httpPostData($url,$data){
	  	$data = JSON($data,false);
	  	$ch = curl_init();
	  	curl_setopt($ch, CURLOPT_URL, $url);
	  	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	  	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	  	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	  	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
	  	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	  	curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
	  	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	  	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	  	$status = curl_exec($ch);
	  	curl_close($ch);
	  	return $status;
	  }
	  

	  /**
	   * 美容项目短信请求
	   * @date: 2015-9-2
	   * @author: 刘炎炎
	   * @return:
	   */
	 	public function sendMassage($phone,$content){
	 		$time = time();
	 		$post_data = array();
	 		$post_data['userid'] = '5710';//企业ID
	 		$post_data['timestamp']=date("YmdHis",$time);//当前时间戳
	 		$post_data['sign']=strtolower(md5('ZK11123456'.(date("YmdHis",$time))));//MD5（账号密码当前时间戳）
	 		$post_data['content'] = $content.'【易美佳人】'; //格式为：内容【签名】
	 		$post_data['mobile'] = $phone;//手机号
	 		$post_data['sendtime'] = ''; //不定时发送，值为‘’，定时发送，输入格式YYYYMMDDHHmmss的日期值
	 		$url='http://xtx.telhk.cn:8080/v2sms.aspx?action=send';
	 		$o='';
	 		foreach ($post_data as $k=>$v)
	 		{
	 			$o .= "$k=".urlencode($v).'&';
	 			//dump($o);
	 		}
	 	
	 		$post_data=substr($o,0,-1);
	 	
	 		$ch = curl_init();
	 	
	 		curl_setopt($ch, CURLOPT_POST, 1);
	 		curl_setopt($ch, CURLOPT_HEADER, 0);
	 		curl_setopt($ch, CURLOPT_URL,$url);
	 		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	 		//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果需要将结果直接返回到变量里，那加上这句。
	 		$result = curl_exec($ch);
	 	}
	 	 
	 	/*  public function sendMassage($phone,$content){
	 	 $time = time();
	 	$nowtime = date("yyyymmddhhiiss",$time);
	 	$sign = 'ZK11123456'.$nowtime;
	 	$qianming = md5($sign);
	 	$qianming = strtolower($qianming);
	 	$post_data = array();
	 	$post_data['userid'] = '5710';//企业ID
	 	$post_data['timestamp']=date("YmdHis",$time);//当前时间戳
	 	$post_data['sign']=md5($sign);//MD5（账号密码当前时间戳）
	 	$post_data['content'] = $content.'【易美佳人】'; //格式为：内容【签名】
	 	$post_data['mobile'] = $phone;//手机号
	 	$post_data['sendtime'] = ''; //不定时发送，值为‘’，定时发送，输入格式YYYYMMDDHHmmss的日期值
	 	$url='http://xtx.telhk.cn:8080/v2sms.aspx?action=send';
	 	$o='';
	 	foreach ($post_data as $k=>$v)
	 	{
	 	$o .= "$k=".urlencode($v).'&';
	 	//dump($o);
	 	}
	 	
	 	$post_data=substr($o,0,-1);
	 	
	 	$ch = curl_init();
	 	
	 	curl_setopt($ch, CURLOPT_POST, 1);
	 	curl_setopt($ch, CURLOPT_HEADER, 0);
	 	curl_setopt($ch, CURLOPT_URL,$url);
	 	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	 	//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果需要将结果直接返回到变量里，那加上这句。
	 	$result = curl_exec($ch);
	 	} */
	 		 
	 		 
	 		 
	 		 
	 	
	 	
	  
	  
	  public function xmlToArray($xml)
	  {
	  	//将XML转为array
	  	$array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
	  	return $array_data;
	  } 
	  public function sendSms($verifycode,$phonenumber){
	  	$data = array (
	  			'action' => 'send', //发送任务命令
	  			'account' => 'emeijia', //账号
	  			'password' => '111111', //密码
	  			'mobile' => $phonenumber, //手机号
	  			'content' => $verifycode, //内容
	  			'sendTime' => time(), //发送时间
	  			'AddSign' => 'Y'  //是否自动加上系统配置默认的签名
	  	);
	  	$url = 'http://www.smswst.com/api/httpapi.aspx?action=send&account='.$data['account'].'&password='.$data['password'].'&mobile='.$data['mobile'].'&content='.$data['content'].'&sendTime=&AddSign=Y';
	  	$return = $this->httpPostData($url);
	  	//dump($return);
	  	$return = $this->xmlToArray($return);
	  	$data['returncode'] = $return['successCounts'];
	  	$data['config'] = serializeMysql($return);
	  	$smsLogic = D('Sms','Logic');
	  	$smsLogic->add($data);
	  }
	  
	  
	  /**
	   * 发送模板短信
	   * @param to 短信接收彿手机号码集合,用英文逗号分开
	   * @param datas 内容数据
	   * @param $tempId 模板Id
	   */
	  function sendTemplateSMS($to,$datas,$tempId)
	  {
	  	//主帐号鉴权信息验证，对必选参数进行判空。
	  	/* $auth=$this->accAuth();
	  	 if($auth!=""){
	  	return $auth;
	  	} */
	  	// 拼接请求包体
	  	if($this->BodyType=="json"){
	  		$data="";
	  		for($i=0;$i<count($datas);$i++){
	  			$data = $data. "'".$datas[$i]."',";
	  		}
	  		$body= "{'to':'$to','templateId':'$tempId','appId':'$this->AppId','datas':[".$data."]}";
	  	}else{
	  		$data="";
	  		for($i=0;$i<count($datas);$i++){
	  			$data = $data. "<data>".$datas[$i]."</data>";
	  		}
	  		$body="<TemplateSMS>
	  		<to>$to</to>
	  		<appId>$this->AppId</appId>
	  		<templateId>$tempId</templateId>
	  		<datas>".$data."</datas>
	  		</TemplateSMS>";
        }
        $this->showlog("request body = ".$body);
	          $Batch = date("YmdHis");
	  		$ServerIP ='sandboxapp.cloopen.com';;
	  		$ServerPort = '8883';;
        $SoftVersion ='2013-12-26';
	          		$AccountSid= '8a48b5514e5298b9014e58f1b70605af';
	          		$this->Handle = fopen($this->Filename, 'a');
	          		$AccountToken = '8e1acf1f3b8e48d4b692f1c03d617836';
	          		// 大写的sig参数
        $sig =  strtoupper(md5($AccountSid. $AccountToken . $Batch));
	          // 生成请求URL
	  
	          $url="https://$ServerIP:$ServerPort/$SoftVersion/Accounts/$AccountSid/SMS/TemplateSMS?sig=$sig";
	          //$result = $this->httpPostData($url);
	          $this->showlog("request url = ".$url);
	          // 生成授权：主帐户Id + 英文冒号 + 时间戳。
	          		$authen = base64_encode($AccountSid. ":" . $Batch);
	          		// 生成包头
	          		$header = array("Accept:application/$this->BodyType","Content-Type:application/$this->BodyType;charset=utf-8","Authorization:$authen");
	          		// 发送请求
	          		$result = $this->curl_post($url,$body,$header);
	          		logs($result);
	          		$this->showlog("response body = ".$result);
	          		if($this->BodyType=="json"){//JSON格式
	          		$datas=json_decode($result);
	          		}else{ //xml格式
	          		$datas = simplexml_load_string(trim($result," \t\n\r"));
	          		}
	          		//  if($datas == FALSE){
	          		//            $datas = new stdClass();
	          		//            $datas->statusCode = '172003';
	          		//            $datas->statusMsg = '返回包体错误';
	          		//        }
	          		//重新装填数据
	          		if($datas->statusCode==0){
	          			if($this->BodyType=="json"){
	              $datas->TemplateSMS =$datas->templateSMS;
	              unset($datas->templateSMS);
	          			}
	          		}
	  
	          		return $datas;
	      }
	      
	      
	      public function sendCodeSms($verifycode,$phonenumber){
	      	$data = array (
	      			'action' => 'send', //发送任务命令
	      			'account' => 'emeijia', //账号
	  				'password' => '111111', //密码
	      			'mobile' => $phonenumber, //手机号
	      			'content' => '【易美佳人】您的验证码为:'.$verifycode, //内容
	      			'sendTime' => time(), //发送时间
	      			'AddSign' => 'Y'  //是否自动加上系统配置默认的签名
	      	);
	      	$url = 'http://www.smswst.com/api/httpapi.aspx?action=send&account='.$data['account'].'&password='.$data['password'].'&mobile='.$data['mobile'].'&content='.$data['content'].'&sendTime=&AddSign=Y';
	      	$return = $this->httpPostData($url);
	      	//dump($return);
	      	$return = $this->xmlToArray($return);
	      	$data['returncode'] = $return['successCounts'];
	      	$data['config'] = serializeMysql($return);
	      	$smsLogic = D('Sms','Logic');
	      	$smsLogic->add($data);
	      }
}
